<?php
require $_SERVER['DOCUMENT_ROOT'].'/../_core/common.php';

$msg = array();

//权限验证
if( Role::init() == false ){
	$msg['error'] = false;
	$msg['string'] = '权限不足！';
	$myjson = json_encode($msg); 
	echo $myjson; 
	exit;
}

require $_SERVER['DOCUMENT_ROOT'].'/../_interface/category.php';

$db = new DB('news');

$id = isset($_POST['id']) ? intval($_POST['id']) : 0;

$category_sql = 'select id,title,parent_id,top_id,child_id from categories where id='.$id.' and is_del=2 limit 1';
$category_rs = $db->query($category_sql)->getOne();

if( $category_rs['id'] <= 0 ){//id不存在
	$msg['error'] = false;
	$msg['string'] = '参数有误！';
}else{
	$parent_sql = 'select title,is_del from categories where id='.$category_rs['parent_id'].' limit 1';
	$parent_rs = $db->query($parent_sql)->getOne();

	if($category_rs['parent_id']==0 && $category_rs['top_id']==0){//是顶级栏目
		//直接更新is_del字段
		$data = array('is_del'=>1);
		$db->table('categories')->where('id='.$id)->update($data)->run();
		
		$msg['error'] = true;
		$msg['string'] = '恢复《'.$category_rs['title'].'》栏目成功!';
	}else{//不是顶级栏目
		$category = new Category($db);

		//更新child_id
		if($category_rs['child_id'] == ''){
			$child_id = $id;
		}else{
			$child_id = $id.','.$category_rs['child_id'];
		}

		//更新当前id记录的原来父级的child_id字段
		$error = false;
		$child_array = explode(',',$child_id);
		
		if($parent_rs['is_del']==1){//父级栏目是否删除
			foreach($child_array as $child){
				$category -> child_add($id,$child);
			}
			
			//更新is_del字段
			$data = array('is_del'=>1);
			$db->table('categories')->where('id='.$id)->update($data)->run();
			
			$msg['error'] = true;
			$msg['string'] = '成功恢复《'.$category_rs['title'].'》栏目!';
		}else{
			$msg['error'] = false;
			$msg['string'] = '请先恢复'.$category_rs['title'].'的上级栏目《'.$parent_rs['title'].'》';
		}
	}
}

$myjson = json_encode($msg); 
echo $myjson; 